import { View } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { useState, useEffect } from "react";
import Loading from "../component/load";
import Main from "../main";
import Utils from "@/utils/index";
import { getStorage } from "@/pages/components/utils";
import { getBaseUrl, requestSystemUrl } from "@/network/baseUrl";
import { HttpGet } from "@/network/servers";
import { useDispatch } from "react-redux";
import { useDocumentTitle, useOnlineCheck } from "@/utils/myUtils";
import useNavLoginPage from "../../../hooks/useNavLoginPage";
import "./index.scss";

const storage = getStorage();

function App() {
  const [init, setInit] = useState(false);
  const dispatch = useDispatch();

  useDocumentTitle("消息中心");
  useNavLoginPage({}, "/pages/messageApp/index");

  const getToken = () => {
    if (Utils.getQueryVariable("env") === "weapp") {
      return Utils.getQueryVariable("lg_tk");
    } else {
      return storage.get("token") || Utils.getQueryVariable("lg_tk");
    }
  };

  // 获取初始数据
  const getCommonData = async (params) => {
    if (process.env.TARO_ENV === "h5") {
      Taro.getSysWeb(
        { sysId: "000", schoolId: Utils.getQueryVariable("schoolId") },
        "web",
        async function (res) {
          dispatch({ type: "SET_MAINSERVER", data: res });
          let MainServerAddr = res;
          HttpGet({
            url: "/api/commons/users/info",
            data: {
              token: params.lg_tk,
            },
          }).then((result) => {
            let userInfo = result.data;
            let userIdentityList = userInfo?.userIdentityList || [];
            let currentIdentity =
              userIdentityList.find((i) => i.identityCode) ||
              userIdentityList[0] ||
              {};

            //针对1月份的版本，接口未返回学校ID需要手动添加 否则不兼容报错
            if (!userInfo.schoolId) {
              userInfo.schoolId = "S-02251247";
            }

            dispatch({
              type: "SET_IDENTITYCODE",
              data: currentIdentity?.identityCode || "",
            });

            let messageId = "210";

            if (userInfo.eduId) {
              dispatch({
                type: "SET_ISEDU",
                data: true,
              });
              messageId = "211";
              userInfo.schoolId = userInfo.eduId;
            }

            useOnlineCheck(MainServerAddr, params.lg_tk, messageId);
            HttpGet({
              url: "/api/commons/schools/school/details",
              data: {
                schoolId: userInfo.schoolId,
              },
            }).then(({ data: response={} }) => {
              userInfo["SchoolID"] = userInfo.schoolId;
              userInfo["SchoolLevel"] = response.schoolLevel;
              userInfo["SchoolType"] = response.schoolType;
              userInfo["UserID"] = userInfo.userId;
              userInfo["UserType"] = userInfo.userType;
              userInfo["UserName"] = userInfo.userName;
              userInfo["PhotoPath"] = userInfo.photoPath;

              HttpGet({
                url: "api/commons/schools//current/term",
                data: {
                  schoolId: userInfo.SchoolID,
                },
              }).then((res2) => {
                dispatch({
                  type: "SET_TERMINFO",
                  data: res2.data,
                });
              });
              dispatch({ type: "SET_USERINFO", data: userInfo });
              Taro.getSysWeb({ sysId: "220" }, "web", function (data) {
                dispatch({ type: "SET_NOTICEADDR", data });
              });
              Taro.getSysWeb({ sysId: "260" }, "web", function (data) {
                dispatch({ type: "SET_OFFICEADDR", data });
              });
              // Taro.getSysWeb({ sysId: '460' }, 'web', function (data) {
              //     dispatch({ type: 'SET_CHATURL', data })
              // })
              setInit(true);
            });
          });
        }
      );
    } else {
      let userInfo = JSON.parse(storage.get("userInfo"));
      dispatch({ type: "SET_USERINFO", data: userInfo });
      Taro.getSysWeb(
        { sysId: "220", schoolId: userInfo.SchoolID },
        "web",
        function (data) {
          dispatch({ type: "SET_NOTICEADDR", data });
        }
      );
    }
  };

  useEffect(() => {
    let params = {} as any;
    if (process.env.TARO_ENV === "h5") {
      if (Utils.getQueryVariable("env") === "weapp") {
        //内嵌进h5的页面
        dispatch({ type: "SET_ENV", data: "weapp" });

        requestSystemUrl("210").then((res) => {
          window.baseUrl = res;
          params = {
            lg_tk: Utils.getQueryVariable("lg_tk") || storage.get("lg_tk"),
            lg_ic: Utils.getQueryVariable("lg_ic"),
            env: Utils.getQueryVariable("env"),
            schoolId: Utils.getQueryVariable("schoolId"),
            baseUrl: res,
          };
          dispatch({ type: "SET_BASEURL", data: res });
          dispatch({ type: "SET_TOKEN", data: getToken() });
          getCommonData(params);
        });
      } else {
        window.baseUrl = getBaseUrl();
        dispatch({ type: "SET_ENV", data: "app" });
        dispatch({ type: "SET_BASEURL", data: getBaseUrl() });
        params = {
          lg_tk: storage.get("lg_tk") || Utils.getQueryVariable("lg_tk"),
          lg_ic: Utils.getQueryVariable("lg_ic") || storage.get("lg_ic"),
          baseUrl: getBaseUrl(),
        };
        dispatch({ type: "SET_TOKEN", data: getToken() });
        getCommonData(params);
      }
    } else {
      //小程序部分（可忽略，目前不使用此方案）
      dispatch({ type: "SET_ENV", data: "weapp" });
      dispatch({ type: "SET_BASEURL", data: getBaseUrl() });
      params = {
        lg_tk: storage.get("lg_tk"),
        lg_ic: storage.get("lg_ic"),
        baseUrl: getBaseUrl(),
      };
      getCommonData(params);
    }
  }, []);

  if (!init) {
    return (
      <View>
        <Loading content="加载中" isOpened={true} />
      </View>
    );
  }

  return <Main />;
}
export default App;
